import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState } from 'react';
import type { UploadFile } from 'antd/es/upload/interface';

const ImageToPdf = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleUpload = async () => {
    const formData = new FormData();
    fileList.forEach((file) => {
      if (file.originFileObj) {
        formData.append('images', file.originFileObj);
      }
    });

    try {
      const response = await fetch('http://localhost:3001/api/images-to-pdf', {
        method: 'POST',
        body: formData,
      });
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'converted.pdf';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        message.success('PDF生成成功！');
        setFileList([]);
      } else {
        message.error('PDF生成失败，请重试！');
      }
    } catch (error) {
      message.error('PDF生成失败，请重试！');
    }
  };

  return (
    <div style={{ textAlign: 'center', padding: '20px' }}>
      <h2>图片转PDF</h2>
      <Upload
        multiple
        listType="picture"
        fileList={fileList}
        onChange={({ fileList }) => setFileList(fileList)}
        beforeUpload={() => false}
        accept="image/*"
      >
        <Button icon={<UploadOutlined />}>选择图片</Button>
      </Upload>
      {fileList.length > 0 && (
        <Button
          type="primary"
          onClick={handleUpload}
          style={{ marginTop: '20px' }}
        >
          生成PDF
        </Button>
      )}
      <p style={{ marginTop: '20px' }}>
        支持多张图片，可拖拽调整顺序，单个文件大小限制为20MB
      </p>
    </div>
  );
};

export default ImageToPdf; 